package com.elai.analytics.controller;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.elai.analytics.domain.ColumnHeader;
import com.elai.analytics.domain.third.CKSpreadReq;
import com.elai.analytics.domain.third.CkKeepResVO;
import com.elai.analytics.domain.third.CkSpreadDetailVO;
import com.elai.analytics.domain.third.CkSpreadVO;
import com.elai.baseconfig.domain.EventItemDO;
import com.elai.baseconfig.service.EventItemService;
import com.elai.common.constant.BusinessConstants;
import com.elai.common.constant.HttpStatus;
import com.elai.common.core.controller.BaseController;
import com.elai.common.core.domain.AjaxResult;
import com.elai.common.utils.DateUtils;
import com.elai.common.utils.ThirdProperties;
import com.elai.common.utils.WebUtils;
import org.apache.commons.collections4.map.HashedMap;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 分布分析Controller
 *
 * @author elai
 * @date 2021-06-19
 */
@RestController
@RequestMapping("/report/spread")
public class SpeadAnalyticsController extends BaseController
{
    private static final Logger log = LoggerFactory.getLogger(SpeadAnalyticsController.class);

    @Autowired
    private ThirdProperties thirdProperties;

    @Autowired
    private EventItemService eventItemService;

    private static final String SPREAD_ANALYSIS ="spread/findSpread";

//
//    @PostMapping("/spreadAnalyQuery")
//    public AjaxResult spreadAnalyQuery(@RequestBody String requestJson)
//    {
//        log.info("keepAnalyQuery："+requestJson);
//        JSONObject paramJson = JSONObject.parseObject(requestJson);
//        JSONObject spreadJson = paramJson.getJSONObject("requestJson");
//
//        JSONArray applicationCodeArray = spreadJson.getJSONArray("applicationCode");
//        JSONArray dateRangeArray = spreadJson.getJSONArray("dateRange");
//        String pageSize = spreadJson.getString("pageSize");
//        String timeType = spreadJson.getString("timeType");
//        String eventType = spreadJson.getString("tventType");
//        int chartType = spreadJson.getInteger("chartType");
//        JSONArray queryItemsArray = spreadJson.getJSONArray("queryItems");
//        JSONArray filterTagsArray = spreadJson.getJSONArray("filterTags");
//
//        JSONArray methodArray = spreadJson.getJSONArray("typeItem");
//
//        String startDate = null;
//        String endDate = null;
//        if (JSONUtil.isNull(dateRangeArray)){
//            startDate = DateUtils.getYYYYMMDD(-6);
//            endDate = DateUtils.getYYYYMMDD(-1);
//        }else{
//            String tempStartDate = dateRangeArray.getString(0);
//            String tempEndDate = dateRangeArray.getString(1);
//            startDate = tempStartDate.length()>10?tempStartDate.substring(0,10):tempStartDate;
//            endDate = tempEndDate.length()>10?tempEndDate.substring(0,10):tempEndDate;
//        }
//
////        Map<String, Object> paramMap =new HashedMap();
//        CKSpreadReq param = new CKSpreadReq();
//        param.setStartDate(startDate);
//        param.setEndDate(endDate);
//        param.setEventName(eventType);
//        param.setGroupBy("time");
//        param.setIsInt("N");
//
//        if (methodArray != null && !methodArray.isEmpty()){
//            param.setMethodName(methodArray.getString(1));
//            param.setFieldName(methodArray.getString(0));
//
//            EventItemDO eventItem = new EventItemDO();
//            eventItem.setEventItemCode(methodArray.getString(0));
//            eventItem.setValueType(BusinessConstants.value_type_int);
//            List<EventItemDO> codeList = eventItemService.selectEventItemList(eventItem);
//            if (codeList != null && codeList.size() > 0){
//                param.setIsInt("Y");
//            }
//        }
//
//        if (applicationCodeArray != null && !applicationCodeArray.isEmpty()){
//            param.setApplicationCodeList(applicationCodeArray.toJavaList(String.class));
//        }
//        param.setJsonParam(spreadJson);
//
//        Map<String,Object> resultMap=new HashMap();
//
//        //列表表头
//        List<ColumnHeader> tableTitle=new ArrayList<ColumnHeader>();
//        tableTitle.add(new ColumnHeader("eventName","指标","",true));
//        tableTitle.add(new ColumnHeader("total","总人数","",true));
//        tableTitle.add(new ColumnHeader("firist","第一日","",true));
//
//        //列表数据
//        List<Map<String,String>> tableData=new ArrayList<>();
//
//        Map<String,String> data2=new HashMap();
//        data2.put("id","2");
//        data2.put("eventName","$APP激活的启动时长");
//        data2.put("total","368");
//        data2.put("firist","28.59");
//        tableData.add(data2);
//
//        Map<String,String> data3=new HashMap();
//        data3.put("id","3");
//        data3.put("eventName","$APP激活的启动时长");
//        data3.put("total","368");
//        data3.put("firist","28.59");
//        tableData.add(data3);
//
//        Map<String,String> data4=new HashMap();
//        data4.put("id","4");
//        data4.put("eventName","$APP激活的启动时长");
//        data4.put("total","645");
//        data4.put("firist","2354359");
//        tableData.add(data4);
//
//        resultMap.put("tableTitle",tableTitle);
//        resultMap.put("tableData",tableData);
//
//        return AjaxResult.success(resultMap);
//    }
    @PostMapping("/spreadAnalyQuery")
    public AjaxResult spreadAnalyQuery(@RequestBody String requestJson)
    {
        log.info("keepAnalyQuery："+requestJson);
        JSONObject paramJson = JSONObject.parseObject(requestJson);
        JSONObject spreadJson = requestJson.isEmpty()?new JSONObject(): paramJson.getJSONObject("requestJson");
        if (JSONUtil.isNull(spreadJson)){
            spreadJson = new JSONObject();
        }
        String startDate = null;
        String endDate = null;

        JSONArray dateArray = spreadJson.getJSONArray("dateRange");
        if (JSONUtil.isNull(dateArray)){
            startDate = DateUtils.getYYYYMMDD(-6);
            endDate = DateUtils.getYYYYMMDD(-1);
        }else{
            String tempStartDate = dateArray.getString(0);
            String tempEndDate = dateArray.getString(1);
            startDate = tempStartDate.length()>10?tempStartDate.substring(0,10):tempStartDate;
            endDate = tempEndDate.length()>10?tempEndDate.substring(0,10):tempEndDate;
        }
        //概要基础指标来源
        if (startDate.equals(endDate) && spreadJson.containsKey("fromQuery")){
            startDate = DateUtils.getOneDayYYYYMMDD(endDate,-6);
        }

        Map<String, Object> paramMap =new HashedMap();
        paramMap.put("startDate",startDate);
        paramMap.put("endDate",endDate);
        paramMap.put("jsonParam",spreadJson);
        paramMap.put("eventName",spreadJson.getString("tventType"));
        paramMap.put("categoryType",spreadJson.getString("categoryType"));
        if (spreadJson.containsKey("applicationCode")){
            JSONArray applicationCodeList = spreadJson.getJSONArray("applicationCode");
            if (applicationCodeList != null && !applicationCodeList.isEmpty()){
                paramMap.put("applicationCodeList",applicationCodeList.toJavaList(String.class));
            }
        }
        JSONArray eventMethodArray = spreadJson.containsKey("typeItem")?spreadJson.getJSONArray("typeItem"):new JSONArray();
        String methodName = "";
        paramMap.put("isInt","N");
        if(eventMethodArray!=null) {
            if (eventMethodArray.size() == 2){
                paramMap.put("methodName",eventMethodArray.getString(1));
                paramMap.put("fieldName",eventMethodArray.getString(0));
                EventItemDO eventItem = new EventItemDO();
                eventItem.setEventItemCode(eventMethodArray.getString(0));
                eventItem.setValueType(BusinessConstants.value_type_int);
                List<EventItemDO> codeList = eventItemService.selectEventItemList(eventItem);
                if (codeList != null && codeList.size() > 0){
                    paramMap.put("isInt","Y");
                }
//                methodName = eventMethodArray.getString(1);
            }else{
                paramMap.put("methodName",eventMethodArray.getString(0));
            }

        }

        JSONObject obj= WebUtils.postCkObj(thirdProperties.getCkUrl(),SPREAD_ANALYSIS,paramMap);
        int subcode = obj.getInteger("code");
        List<CkSpreadVO> overvivwVOList=new ArrayList<>();
        if(HttpStatus.CK_SUCCESS == subcode){
            overvivwVOList = JSON.parseArray(obj.getString("data"), CkSpreadVO.class);
        }

        Map<String,Object> resultMap=new HashMap();

        List<CkSpreadDetailVO> detailVOList = null;
        //列表表头
        List<ColumnHeader> tableTitle=new ArrayList<ColumnHeader>();
        tableTitle.add(new ColumnHeader("eventName","用户行为日期","",true));
        tableTitle.add(new ColumnHeader("total","总人数","",true));
        if (overvivwVOList != null && overvivwVOList.size() > 0){
            detailVOList = overvivwVOList.get(0).getDetailVOList();
            if (detailVOList != null && detailVOList.size() > 0){
                for (CkSpreadDetailVO detailVO : detailVOList){
                    tableTitle.add(new ColumnHeader(detailVO.getTitle(),detailVO.getTitle(),"",true));
                }
            }else{
                tableTitle.add(new ColumnHeader("title","总次数","",true));
            }
        }else{
            tableTitle.add(new ColumnHeader("title","总次数","",true));
        }

        resultMap.put("tableTitle",tableTitle);

        //列表数据
        List<Map<String,String>> tableData=new ArrayList<>();
        for (CkSpreadVO spreadVO : overvivwVOList){
            Map<String,String> data=new HashMap();
            data.put("id",spreadVO.getEventGroup());
            data.put("eventName",spreadVO.getEventGroup());
            data.put("total",spreadVO.getTotal()+"");
            if (detailVOList != null && detailVOList.size() > 0){
                for (CkSpreadDetailVO detailVO : detailVOList){
                    data.put(detailVO.getTitle(),detailVO.getTitleValue()+"");
                }
            }else{
                data.put("title",spreadVO.getEventCount());
            }

            tableData.add(data);
        }

//        Map<String,String> data2=new HashMap();
//        data2.put("id","2");
//        data2.put("eventName","$APP激活的启动时长");
//        data2.put("total","368");
//        data2.put("firist","28.59");
//        tableData.add(data2);
//
//        Map<String,String> data3=new HashMap();
//        data3.put("id","3");
//        data3.put("eventName","$APP激活的启动时长");
//        data3.put("total","368");
//        data3.put("firist","28.59");
//        tableData.add(data3);
//
//        Map<String,String> data4=new HashMap();
//        data4.put("id","4");
//        data4.put("eventName","$APP激活的启动时长");
//        data4.put("total","645");
//        data4.put("firist","2354359");
//        tableData.add(data4);

        resultMap.put("tableData",tableData);


        return AjaxResult.success(resultMap);
    }

}
